import React, { useEffect, useState } from 'react'
import style from './Index.module.less'
import { Table, Button, Space, message } from 'antd'
import { getColumns } from './util'
import { awaitWrap, confirmAction } from '@js/tool'
import { getListRequest } from './ajax'
import SearchFrom from './components/Form/Index'
import { useDispatch } from 'react-redux'
import { DownloadOutlined, PlusOutlined } from '@ant-design/icons'
import { addWindow } from '@src/redux/actions'
import { json2Excel } from '@js/excel'
import moment from 'moment'

async function getList (condition, pageSize, current, setLoading, setList, setTotal) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(condition, pageSize, current))
  setLoading(false)
  if (e === null && d !== null) {
    d.list.forEach((li, i) => {
      li.index = i + 1 + (current - 1) * pageSize
    })
    setList(d.list)
    setTotal(d.total)
  }
}

// 获取当前查询条件的全部数据，并下载excel
async function downloadExcel (condition) {
  const hide = message.loading('导出中', 300)
  const [e, d] = await awaitWrap(getListRequest(condition, 1000000, 1))
  hide()
  if (e === null && d !== null) {
    const list = d.list.map((l, i) => {
      let t
      if (l.closure_datetime) {
        t = moment(`${moment(l.closure_datetime * 1000).format('YYYY-MM-DD')} 00:00:00`).toDate()
      }
      return {
        序号: i + 1,
        案号: l.caseno_desc,
        申请人: l.applicant,
        被申请人: l.respondent,
        案由: l.cause_action,
        '和解金额(元)': l.dispute_amount || 0,
        // 仲裁调解员: l.arbitrator,
        和解事项: l.claim_items,
        和解内容: l.claim,
        和解时间: t,
        立案部意见: l.docket_remark,
        秘书长意见: l.audit_remark
      }
    })
    json2Excel([{ data: list, sheetname: '调解案件导出列表' }], '调解案件导出列表')
  }
}

function Main ({ title }) {
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [current, setCurrent] = useState(1)
  const [list, setList] = useState([])
  const [condition, setCondition] = useState([])
  const [pagination, setPagination] = useState({
    total,
    pageSize,
    current,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  useEffect(() => {
    getList(condition, pageSize, current, setLoading, setList, setTotal)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageSize, current, condition])
  useEffect(() => {
    setPagination({
      ...pagination,
      total,
      pageSize,
      current
    })
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [total, pageSize, current])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchFrom onChange={(c) => { setCondition(c); setCurrent(1) }} />
      <div className={style['table-btns-line']}>
        <Space size='large'>
          <Button
            type='primary' onClick={() => {
              dispatch(addWindow({ id: 'TJCreate', title: '融入基层治理案件', componentName: 'TJCaseEdit', forceRefresh: false, meta: { } }))
            }} icon={<PlusOutlined />}
          >添加融入基层治理案件
          </Button>
          <Button type='primary' ghost onClick={() => confirmAction('您确定要导出excel吗？', () => downloadExcel(condition))} icon={<DownloadOutlined />}>导出excel</Button>
        </Space>
      </div>
      <div className={style.table}>
        <Table rowKey='id' columns={getColumns(dispatch, () => getList(condition, pageSize, current, setLoading, setList, setTotal))} loading={loading} dataSource={list} pagination={pagination} onChange={({ current, pageSize }) => { setPageSize(pageSize); setCurrent(current) }} />
      </div>
    </div>
  )
}

export default Main
